package learningThread.instance.dcl;

/**
 * java 双重锁检测
 */
public class DoubleCheckLock {

    private DoubleCheckLock(){

    }

    private static DoubleCheckLock dcl = null;

    /**
     * DCL 写法
     * @return
     */
    public static DoubleCheckLock getInstance() {
        //1.第一次检测
        if (dcl == null) {
            System.out.println(Thread.currentThread().getName()+"进入第一次检测");
            //2.加锁
            synchronized (DoubleCheckLock.class) {
                System.out.println(Thread.currentThread().getName()+"进入锁");
                //3.第二次检测
                if (dcl == null) {
                    System.out.println(Thread.currentThread().getName()+"进入第二次检测");
                    dcl = new DoubleCheckLock();
                }
            }
        }
        return dcl;
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                DoubleCheckLock instance = DoubleCheckLock.getInstance();
            }
        },"thread1");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                DoubleCheckLock instance = DoubleCheckLock.getInstance();
            }
        },"thread2");
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                DoubleCheckLock instance = DoubleCheckLock.getInstance();
            }
        },"thread3");

        thread1.start();
        thread2.start();
        thread3.start();
    }


}
